package cn.chenc.framework.security.handle;

import cn.chenc.framework.core.consts.HttpStatus;
import cn.chenc.framework.core.model.request.RequestHolder;
import cn.chenc.framework.core.model.response.AjaxResult;
import cn.chenc.framework.core.util.JsonUtils;
import cn.chenc.framework.core.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录失败处理
 */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("登录失败", request.getRequestURI());
        RequestHolder.renderString(response, JsonUtils.objectToJson(AjaxResult.error(code,msg)));

    }


}
